//
//  AppDelegate.swift
//  GhostWorld
//
//  Created by Kam on 2018/4/1.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit
import CoreData
import Sync
import AVFoundation
import SwiftyStoreKit
import PKHUD


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate ,JPUSHRegisterDelegate{
    
    
    
    // MARK: - Private vars
    
    
    
    // MARK: - Private methods
    
    private func prepareGlobalUI() {
        UINavigationBar.appearance().shadowImage = UIImage()
    }
    
    private func setAudioSessionCategory() {
        let session = AVAudioSession.sharedInstance()
        do {
            try session.setCategory(.playback, mode: .default)
            loggingPrint("Set application audio session category to AVAudioSessionCategoryPlayback")
        } catch {
            loggingPrint("Set application audio session category failed!")
        }
    }
    
    private func prepareUmeng() {
        
        //------ common
        
        UMConfigure.initWithAppkey(ThirdPartyKeys.umengAppKey, channel: "AppStore")
        
        //------ share
        
        /* 设置微信的appKey和appSecret */
        UMSocialManager.default().setPlaform (
            .wechatSession,
            appKey: ThirdPartyKeys.wechatAppID,
            appSecret: ThirdPartyKeys.wechatAppSecret,
            redirectURL: "http://mobile.umeng.com/social"
        )
        
        /*
         * 移除相应平台的分享，如微信收藏
         */
        //[[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
        
        /* 设置分享到QQ互联的appID
         * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
         */
        UMSocialManager.default().setPlaform (
            .QQ,
            appKey: ThirdPartyKeys.qqAppID,
            appSecret: nil,
            redirectURL: "http://mobile.umeng.com/social"
        )
        
        /* 设置新浪的appKey和appSecret */
        UMSocialManager.default().setPlaform (
            .sina,
            appKey: ThirdPartyKeys.weiboAppKey,
            appSecret: ThirdPartyKeys.weiboAppSecret,
            redirectURL: "https://sns.whalecloud.com/sina2/callback"
        )
        
        //    try! IAPPurchasedItem.add(date: Date(), contentType: "album", id: "10058", name: "漂（全两集）", coverURLString: "\(APIURLStrings.imagePrefix)/system/albums/covers/000/010/058/original/gw_2F2017-04-03-05-51-35.jpg?1522118511")
        
        //------ settings
        
        //    UMSocialGlobal.shareInstance().isUsingWaterMark = true
        //    UMSocialGlobal.shareInstance().isUsingHttpsWhenShareContent = false
    }
    
    // MARK: - Public vars
    
    var window: UIWindow?
    
    var downloadBackgroundSessionCompletionHandler : (() -> Void)?
    
    // MARK: - Lifecycle
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        IAPManger.shared.prepare()
        setAudioSessionCategory()
        prepareGlobalUI()
        PlayCore.shared.registerMPRemoteCommand()
        
        LocalFileManager.shared.prepareAudioCacheFolder()
        BasicDataManager.shared.processBasicOnlineData()
        
        AudioDownloadManager.shared.prepare()
        let _ = AudioDownloadManager.shared.getAllAlbumsHaveDownloadedAudios()
        
        NowPlayingManager.shared.prepare()
        
        // Umeng
        prepareUmeng()
        
        // upload pending purchase info
        PurchaseUploader.shared.upload()
        //    SwiftyStoreKit.restorePurchases(atomically: true) { results in
        //      if results.restoreFailedPurchases.count > 0 {
        //        print("Restore Failed: \(results.restoreFailedPurchases)")
        //      }
        //      else if results.restoredPurchases.count > 0 {
        //        print("Restore Success: \(results.restoredPurchases)")
        //      }
        //      else {
        //        print("Nothing to Restore")
        //      }
        //    }
        
        let entity = JPUSHRegisterEntity.init()
        entity.types = Int(JPAuthorizationOptions.alert.rawValue|JPAuthorizationOptions.badge.rawValue|JPAuthorizationOptions.sound.rawValue)
        JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
        JPUSHService.setup(withOption: launchOptions, appKey:"a7493e95fe95242ad73e66e6", channel: "App Store", apsForProduction: false)
        JPUSHService.registrationIDCompletionHandler { (resCode, registrationID) in
            if resCode == 0 {
                print("registrationID获取成功：\(registrationID!)")
            }
            else{
                print("registrationID获取失败，code：\(resCode)")
            }
        }
        
        return true
    }
    
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
        NowPlayingManager.shared.pausePlayTimer()
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        NowPlayingManager.shared.savePlaytimeBeforeAppTerminated()
    }
    
    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
        UIApplication.shared.applicationIconBadgeNumber = 0
        JPUSHService.setBadge(0)
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        NowPlayingManager.shared.resumePlayTimer()
    }
    
    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
        NowPlayingManager.shared.savePlaytimeBeforeAppTerminated()
    }
    // MARK:- 极光推送
    
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        let userInfo = notification.request.content.userInfo
        if notification.request.trigger!.isKind(of: UNPushNotificationTrigger.classForCoder()) {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        completionHandler(1<<2)
        
    }
    
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        
        let userInfo = response.notification.request.content.userInfo
        if response.notification.request.trigger!.isKind(of: UNPushNotificationTrigger.classForCoder()) {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        completionHandler()
    }
    
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, openSettingsFor notification: UNNotification!) {
        
    }
    
    func jpushNotificationAuthorization(_ status: JPAuthorizationStatus, withInfo info: [AnyHashable : Any]!) {
        
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        
        JPUSHService.registerDeviceToken(deviceToken)
        
    }
    
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        let result = UMSocialManager.default().handleOpen(url, options: options)
        if result == false {
            // other call backs
            
            // MARK: - Handle Alipay callback
            
            //      if (url.host == "safepay") {
            //        AlipaySDK.defaultService().processOrder(withPaymentResult: url) { response in
            //          AlipayManager.shared.process (
            //            orderResponse: response,
            //            completion: { (success, message) in
            //              if success {
            //                HUD.flash(.labeledSuccess(title: message, subtitle: nil), delay: 1.5)
            //              } else {
            //                HUD.flash(.labeledError(title: message, subtitle: nil), delay: 1.5)
            //              }
            //          })
            //        }
            //      }
            
            return true
        } else {
            return result
        }
    }
    
    func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
        downloadBackgroundSessionCompletionHandler = completionHandler
    }
    
    // MARK: - Core Data stack
    
    lazy var dataStack: DataStack = {
        let stack = DataStack(modelName: "GhostWorld")
        return stack
    }()
    
    // MARK: - Core Data Saving support
    
    func saveContext () {
        let context = dataStack.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
}


// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromAVAudioSessionCategory(_ input: AVAudioSession.Category) -> String {
    return input.rawValue
}
